import { Vector3 } from "three";
import { App, Easings, Marker3D, animationAsync, generateUUID, getObjectAnchorPoint, randInt, sleep } from "vjmap3d";
import CarInfo  from "../components/CarInfo.vue"
import { createApp } from "vue";
import { getcashWindowMarkerInfo } from "./cashwindow";
// 车的相关方法

const  carModelsName = [
    {
        name: "bigTruck",
        tag: "大卡车"
    },
    {
        name: "smallTruck",
        tag: "小货车"
    },
    {
        name: "coach",
        tag: "客车"
    },
    {
        name: "ambulance",
        tag: "救护车"
    },
    {
        name: "fireTruck",
        tag: "消防车"
    },
    {
        name: "policeCar",
        tag: "警车"
    },
]
// 在一个车道内生成一辆车
export const buildCarInRoad = async (app: App, roadNo: number, pole: {
    openPole: () => {},
    closePole: () => {} 
}) => {
    let dirMovingforward = roadNo > 4;
    // 随机延迟一点时间
    await sleep(Math.random() * 5000);
    // 根据模型获取车道的坐标
    const road = app.getLoadedResources().getModel("toll").getObjectByName('CD0' + roadNo);
    // 获取位置 
    const position = new Vector3();
    road.getWorldPosition(position); 
    const targetPostion = position.clone(); // 抬杆地
    const endPosition = position.clone(); // 最后的地方

    targetPostion.z += 2 * (dirMovingforward ? 1 : -1); // 离抬杆稍远点
   
    position.z += 50 * (dirMovingforward ? 1 : -1) // 前面四个车道在后面，后面四个车道车前进
    endPosition.z -= 60 * (dirMovingforward ? 1 : -1)
    let carIndex =  randInt(0, carModelsName.length - 1);
    let modelCar = app.getLoadedResources().cloneModel(carModelsName[carIndex].name, {
        // 默认位置在模型的中心点，需要设置对齐方式
        anchor: dirMovingforward ? 'back-bottom' : "front-bottom",
         // 反方向的车需要调头下
        rotation: !dirMovingforward ? [0, Math.PI, 0] : undefined,
    });
    
    // 对齐方式所获取到的偏移量坐标值,后面每设置坐标时，都要加上这个偏移量
    let posOffset = new Vector3(0, 0, modelCar.position.z);
    modelCar.position.copy(position).add(posOffset);
    modelCar.addTo(app);

    let startPosition = modelCar.position.clone();
    await animationAsync({
        duration: 3000,
        easing: Easings.easeInOutSine,
        // @ts-ignore
        onProgress: (target, key, start, end, alpha, reversed) => {
            modelCar.position.copy(startPosition.clone().lerp(targetPostion, alpha)).add(posOffset)
        }
    })
    // 显示车辆信息
    // 创建车辆窗口信息详情面板
    let el = document.createElement('div');
    let vueApp = createApp(CarInfo, {
        carId: '京B' + generateUUID().substring(0, 5).toUpperCase(),
        driverName: '司机' + randInt(0, 1000),
        carType: carModelsName[carIndex].tag,
        carState: Math.random() < 0.1 ? '异常' : "正常"
    });
    let vueComp = vueApp.mount(el)
    let carMarker = new Marker3D({
      element: el,
      width: 8,
      anchor: 'bottom'
    })
    carMarker.signal.onRemove.addOne(() => vueApp.unmount()); // 移除时卸载组件
    let carTopPos = getObjectAnchorPoint(modelCar.node, "middle-top", true);
    carMarker.setPosition(carTopPos);
    carMarker.addTo(modelCar)
    pole.openPole(); // 抬杆
    await sleep(2000) ;// 抬杆需要二秒
    sleep(1000).then(async () => {
        pole.closePole(); // 车通过1s后关闭抬杆
        // @ts-ignore
        await vueComp.exit(); //等退出动画结束
        carMarker.remove(); // 移除
    })
    // 如果收费窗口的信息窗口打开了，需要更新下过车的数量
    let cashWndMarker = getcashWindowMarkerInfo();
    // @ts-ignore
    if (cashWndMarker && cashWndMarker.userData.name == `SF00${roadNo}`) {
        // 如果收费窗口的信息窗口打开了，并且是当前站台的窗口
        // @ts-ignore
        cashWndMarker.userData.vueData.carCount++;
    }
    // 车驶出动画
    await animationAsync({
        duration: 3000,
        easing: Easings.easeInOutSine,
        // @ts-ignore
        onProgress: (target, key, start, end, alpha, reversed) => {
            modelCar.position.copy(targetPostion.clone().lerp(endPosition, alpha)).add(posOffset)
        }
    });
    modelCar.remove(); // 删除
}